package cc.site.main.controller;

import cc.site.common.utils.R;
import cc.site.main.bean.dto.OrderDto;
import cc.site.main.service.TblOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yangruomao
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/order")
@Api(tags = "订单管理")
public class TblOrderController {

    @Autowired
    private TblOrderService orderService;

    @GetMapping
    @ApiOperation("查询所有订单，按日期降序")
    public R list() {
        List<OrderDto> list = orderService.listInfo().stream()
                .sorted(Comparator.comparing(OrderDto::getGmtCreate).reversed()) // 按gmtCreateTime降序排序
                .collect(Collectors.toList());

        return R.ok().data("list", list);

    }

    @GetMapping("/forUser/{userId}")
    @ApiOperation("按 userId 查询所有订单")
    public R listByUserId(@PathVariable("userId") Integer userId) {
        List<OrderDto> list = orderService.listInfo().stream()
                .filter(x->x.getUser().getId().equals(userId))
                .sorted(Comparator.comparing(OrderDto::getGmtCreate).reversed()) // 按gmtCreateTime降序排序
                .collect(Collectors.toList());

        return R.ok().data("list", list);
    }


    @DeleteMapping("/{orderId}")
    @ApiOperation("删除订单")
    public R delete(@PathVariable("orderId") Integer orderId) {
        return R.ok().data("list", orderService.removeById(orderId));
    }

    /**
     * 按订单号查询订单
     */
    @GetMapping("/{orderId}")
    @ApiOperation("按订单号查询订单")
    public R search(@PathVariable("orderId") Integer orderId) {
        OrderDto orderDto = orderService.listInfo().stream()
                .filter(x->x.getId().equals(orderId))
                .findFirst()
                .orElse(null);

        return R.ok().data("order", orderDto);
    }

}
